package com.kpi.processflow.node;

import com.kpi.processflow.annotation.TreeNode;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

/**
 * @author Kevin Liu
 * @date 2020/5/3 4:50 下午
 */
@Component
public class NodeBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private NodeRegistry nodeRegistry;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        TreeNode treeNode = AnnotationUtils.findAnnotation(AopUtils.getTargetClass(bean), TreeNode.class);
        if (null==treeNode) {
            return bean;
        }
        if(!ClassUtils.isAssignableValue(Node.class,bean)) {
            throw new BeanCreationException(bean.getClass() + "  doesn't implement node interface");
        }
        Node obj  = (Node)bean;
        String code = obj.getNodeCode();
        nodeRegistry.register(code,obj);
        return bean;
    }
}
